package cn.xo68.ide.plugin.common.ui.generate;

import cn.xo68.ide.plugin.common.domain.CodeGenerateInfo;
import cn.xo68.ide.plugin.common.domain.TableModuleConfig;
import com.wy2.generator.database.common.DatabaseMetaDataEntity;

import javax.swing.event.ChangeListener;

/**
 * 代码生成节点构造者
 * @author wuxie
 * @date 2018-11-25
 */
public final class CodeGenerateNodeBuilder {

    public static CodeGenerateNodeBuilder getInstance(){
        return new CodeGenerateNodeBuilder();
    }

    private final CodeGenerateNode root;

    public CodeGenerateNodeBuilder() {
        this.root = new CodeGenerateNode(null);
    }

    public CodeGenerateNodeBuilder adapter(DatabaseMetaDataEntity databaseMetaDataEntity, TableModuleConfig tableModuleConfig, CodeGenerateInfo codeGenerateInfo, ChangeListener checkStateChangeListener){
        databaseMetaDataEntity.getTables().forEach((table)->{
            if(tableModuleConfig!=null && tableModuleConfig.containsKey(table.getSqlName())){
                table.setModule(tableModuleConfig.get(table.getSqlName()));
            }
            final boolean selected= codeGenerateInfo!=null ? codeGenerateInfo.exists(table.getSqlName()) : true;
            CodeGenerateNode tableNode=new CodeGenerateNode(new CodeGenerateTableContext(selected, checkStateChangeListener, table));
            table.getColumns().forEach((databaseColumn -> {
                CodeGenerateNode columnNode=new CodeGenerateNode(new CodeGenerateColumnContext(selected, checkStateChangeListener, databaseColumn));
                tableNode.add(columnNode);
            }));
            CodeGenerateNodeBuilder.this.root.add(tableNode);
        });
        return this;
    }

    public CodeGenerateNode build(){
        return root;
    }
}
